const Router = require("koa-router");
const util = require("util");
const axios = require("axios");
const { Sequelize } = require("sequelize");
const { RegisterValidator, EmailValidator } = require("../../validators/user");
const { InviteCodeValidator } = require("../../validators/token");
const { Enroll } = require("@models/enroll");
const { User } = require("@models/user");
const { Auth } = require("@middlewares/auth");
const { Activity } = require("@models/activity");
const { UserPoint, PointRecord } = require("@models/point");
const { Admin } = require("@models/admin");
const { Rebate, RebateRecord } = require("@models/rebate");
const { operatorPoint } = require("@services/operatorPoint");
const { Alioss } = require("@services/alioss");
const { Favor } = require("@models/favor");
const { News } = require("@models/news");
const { IdCard } = require("@models/idcard");
const { Op } = require("sequelize");

const router = new Router({
  prefix: "/v1/user",
});
// 获取用户积分
router.post("/point/count", new Auth().m, async (ctx) => {
  const count = await UserPoint.sum("point", { where: { uid: ctx.auth.uid } });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    count: count ? count : 0,
  };
});

// 用户注册
router.post("/register", async (ctx) => {
  const v = await new RegisterValidator().validate(ctx);
  const user = {
    email: v.get("body.email"),
    password: v.get("body.password2"),
    user_name: v.get("body.user_name"),
  };

  const r = await User.create(user);

  ctx.body = {
    code: 200,
    msg: "注册成功",
  };
});

// 用户收藏数
router.get("/get_info/num", new Auth().m, async (ctx) => {
  const enroll_num = await Enroll.count({
    where: {
      uid: ctx.auth.uid,
    },
  });

  const fav_num = await Favor.count({
    where: {
      uid: ctx.auth.uid,
    },
    include: [
      {
        model: News,
        attributes: { exclude: ["content"] },
        where: { is_del: true },
      },
    ],
  });

  const fans = await User.count({
    where: {
      pid: ctx.auth.uid,
    },
  });
  ctx.body = {
    code: 200,
    data: { enroll_num: enroll_num, fav_num: fav_num, fans: fans },
  };
});

// 获取用户信息
router.get("/get_info", new Auth().m, async (ctx) => {
  const userInfo = await User.findOne({
    where: {
      uid: ctx.auth.uid,
    },
    attributes: {
      exclude: ["password"],
    },
    include: [
      {
        model: IdCard,
        attributes: ["sex", "birthday", "address"],
        required: false,
      },
    ],
  });
  if (!userInfo) {
    throw new global.errs.AuthFailed("找不到该用户");
  }
  ctx.body = {
    code: 200,
    data: userInfo,
  };
});

// 更新用户数据啊1
router.post("/update", new Auth().m, async (ctx) => {
  const { uid, point, power, pid, cid, openid, status, inviteCode, ...user } =
    ctx.request.body;

  if (user.avatar) {
    const user2 = await User.findOne({ where: { uid: ctx.auth.uid } });
    await Alioss.del(user2.avatar);
  }

  const updatedInfo = await User.update(user, {
    where: {
      uid: ctx.auth.uid,
    },
  });

  if (!updatedInfo) {
    throw new global.errs.AuthFailed("用户信息更新失败");
  }

  ctx.body = {
    code: 200,
    msg: "更新成功",
  };
});

// 验证邮箱
router.post("/validate_email", async (ctx) => {
  const v = await new EmailValidator().validate(ctx);
  ctx.body = {
    code: 200,
    msg: "可以注册邮箱",
  };
});

// 验证邀请码
router.post("/validate_invite", new Auth().m, async (ctx) => {
  const { inviteCode } = ctx.request.body;
  const v = await new InviteCodeValidator().validate(ctx);
  const p_user = await User.findOne({
    where: {
      inviteCode: inviteCode,
    },
  });

  if (!p_user) {
    throw new global.errs.AuthFailed("验证码不存在");
  }

  const user = await User.findOne({
    where: {
      uid: ctx.auth.uid,
    },
  });

  if (user.pid) {
    throw new global.errs.AuthFailed("你已经被邀请过了");
  }

  if (p_user.uid == ctx.auth.uid) {
    throw new global.errs.AuthFailed("不能自己邀请自己");
  }

  const user_p = await User.findOne({
    where: { pid: ctx.auth.uid, uid: p_user.uid },
  });

  if (user_p) {
    throw new global.errs.AuthFailed("您不能被自己的粉丝邀请");
  }

  await User.update(
    { pid: p_user.uid },
    {
      where: {
        uid: ctx.auth.uid,
      },
    }
  );
  // 邀请成功后增加积分
  await operatorPoint.add(p_user, 1, "邀请注册返利");

  ctx.body = {
    code: 200,
    msg: "邀请成功",
  };
});

// 我的活动订单列表
router.post("/activity/list", new Auth().m, async (ctx) => {
  const {
    page = 1,
    pageSize = 10,
    enroll_status,
    enroll_finish,
  } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  let where = {};
  if (enroll_status == 0 || enroll_status) {
    where = {
      enroll_status: enroll_status,
      enroll_finish: enroll_finish,
      uid: ctx.auth.uid,
    };
  } else {
    where = {
      uid: ctx.auth.uid,
    };
  }
  const { count: total, rows } = await Enroll.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]], // 排序
    include: [
      { model: Activity, where: { is_destroy: true }, required: false },
    ],
  });

  ctx.body = {
    msg: "查询成功",
    code: 200,
    total,
    data: rows,
  };
});

// 获取我的粉丝列表
router.post("/fans/list", new Auth().m, async (ctx) => {
  const { count: total, rows } = await User.findAndCountAll({
    where: { pid: ctx.auth.uid },
  });

  ctx.body = {
    msg: "查询成功",
    code: 200,
    total,
    data: rows,
  };
});

// 获取微信小程序手机号
router.post("/wx/phone", new Auth().m, async (ctx) => {
  const { code } = ctx.request.body;

  const url = util.format(
    global.config.wx.tokenUrl,
    global.config.wx.appId,
    global.config.wx.appSecret
  );

  const result = await axios.get(url);
  if (result.status !== 200) {
    throw new global.errs.AuthFailed("token获取失败");
  }
  const errCode = result.data.errcode;
  const errMsg = result.data.errmsg;
  if (errCode) {
    throw new global.errs.AuthFailed("token获取失败: " + errMsg);
  }

  const token = result.data.access_token;

  const url2 = util.format(global.config.wx.getPhoneUrl, token);
  const result2 = await axios.post(url2, { code });
  if (result2.status !== 200) {
    throw new global.errs.AuthFailed("手机号获取失败");
  }
  const errCode2 = result2.data.errcode;
  const errMsg2 = result2.data.errmsg;
  if (errCode2) {
    throw new global.errs.AuthFailed("手机号获取失败: " + errMsg2);
  }
  const phone = result2.data.phone_info.purePhoneNumber;

  await User.update(
    { phone: parseInt(phone) },
    { where: { uid: ctx.auth.uid } }
  );
  const user = await User.findOne({
    where: { uid: ctx.auth.uid },
  });
  if (!user) {
    throw new global.errs.AuthFailed("手机号绑定失败");
  }
  ctx.body = {
    code: 200,
    msg: "绑定成功",
    data: user,
  };
});

// 积分操作记录
router.post("/record_list", new Auth().m, async (ctx, next) => {
  // 查询条件
  const { page=1, pageSize =10 ,start_time,end_time} = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = {
    uid: ctx.auth.uid,
    created_at: {
      [Op.gte]: start_time,
      [Op.lte]: end_time,
    },
  };
  const { count: total, rows } = await PointRecord.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]], // 排序
    include: [
      {
        model: Admin,
        where: { admin_id: Sequelize.col("PointRecord.operator_id") },
        required: false,
      },
    ],
  });

  const add_point_count = await PointRecord.sum("add_point", {
    where,
  });
  const remove_point_count = await PointRecord.sum("remove_point", {
    where,
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    add_point_count: add_point_count || 0,
    remove_point_count: remove_point_count || 0,
    data: rows,
  };
});

// 结算记录详情
router.post("/rr/detail_list", new Auth(7).m, async (ctx, next) => {
  const { rr_id } = ctx.request.body;
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  // 查询回扣详情列表
  const { count: total, rows } = await Rebate.findAndCountAll({
    where: { rr_id },
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]],
    include: [
      {
        model: User,
        required: false,
      },
    ],
    paranoid: false,
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 查询结算记录
router.post("/rr/list", new Auth(7).m, async (ctx, next) => {
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  const { count: total, rows } = await RebateRecord.findAndCountAll({
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]],
    where: { uid: ctx.auth.uid },
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 查询结算记录
router.post("/rr/list", new Auth(7).m, async (ctx, next) => {
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  const { count: total, rows } = await RebateRecord.findAndCountAll({
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]],
    where: { uid: ctx.auth.uid },
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 获取回扣列表
router.post("/rebate/list", new Auth(7).m, async (ctx, next) => {
  const { page = 1, pageSize = 10,  settle } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = { pid: ctx.auth.uid, deleted_at: settle ? { [Op.ne]: null } : null };

  const count_money = await Rebate.sum("rebate_money", { where });

  const { count: total, rows } = await Rebate.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]],
    include: [
      {
        model: User,
        required: false,
      },
    ],
    paranoid: false,
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    count_money: count_money,
    data: rows,
  };
});


module.exports = router;
